package org.bjf.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.SocketConfig;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author bjf
 */
public class Http {

  public static final String DEFAULT_CHARSET = "UTF-8";
  private static Logger log = LoggerFactory.getLogger(Http.class);
  private static CloseableHttpClient httpClient;
  private static PoolingHttpClientConnectionManager cm;
  private static ResponseHandler<byte[]> responseHandler = null;

  static {
    //===1.设置ConnectionManager
    cm = new PoolingHttpClientConnectionManager();
    // 最大连接数
    cm.setMaxTotal(50);
    // 每路由的最大连接数，默认值是2
    cm.setDefaultMaxPerRoute(10);

    //===2.设置httpClient
    httpClient = HttpClientBuilder.create()
        .useSystemProperties()
        // 线程池
        .setConnectionManager(cm)
        // 请求设置
        .setDefaultRequestConfig(
            RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build())
        // 超时
        .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(5000).build())
        .build();

    //===3.响应Handler
    responseHandler = new ResponseHandler<byte[]>() {
      @Override
      public byte[] handleResponse(HttpResponse httpResponse) throws IOException {
        StatusLine statusLine = httpResponse.getStatusLine();
        HttpEntity entity = httpResponse.getEntity();
        final byte[] bodyBytes;
        if (entity != null) {
          bodyBytes = EntityUtils.toByteArray(entity);
        } else {
          bodyBytes = new byte[0];
        }
        if (statusLine.getStatusCode() >= 300) {
          log.error("请求失败：code{}, reason:{},content:{}",
              statusLine.getStatusCode(), statusLine.getReasonPhrase(),
              new String(bodyBytes, DEFAULT_CHARSET));
        }
        return bodyBytes;
      }
    };

    //===4.关闭钩子
    shutdownHook();
  }

  private static void shutdownHook() {
    Runtime.getRuntime().addShutdownHook(new Thread("thread-http.shutdown") {
      @Override
      public void run() {
        try {
          httpClient.close();
        } catch (IOException ignore) {
          log.error("httpClient 关闭失败", ignore);
        }
      }
    });
  }

  public static String get(String url) {
    return get(url, null);
  }

  public static String get(String url, Map<String, Object> params) {
    try {
      return new String(getByte(url, params, null), DEFAULT_CHARSET);
    } catch (UnsupportedEncodingException ignore) {
      //永远不可能抛出该异常
      throw new RuntimeException(ignore);
    }
  }

  public static String get(String url, Map<String, Object> params, Map<String, String> headers) {
    try {
      return new String(getByte(url, params, headers), DEFAULT_CHARSET);
    } catch (UnsupportedEncodingException ignore) {
      //永远不可能抛出该异常
      throw new RuntimeException(ignore);
    }
  }

  public static byte[] getByte(String url, Map<String, Object> params,
      Map<String, String> headers) {

    //===1.组装url
    if (params != null && params.size() > 0) {
      List<NameValuePair> nvps = new ArrayList<>(params.size());
      for (Map.Entry<String, Object> param : params.entrySet()) {
        nvps.add(new BasicNameValuePair(param.getKey(), param.getValue().toString()));
      }
      String queryString = URLEncodedUtils.format(nvps, DEFAULT_CHARSET);
      url = url + "?" + queryString;
    }

    HttpGet get = new HttpGet(url);

    return execute(get, headers);
  }


  public static String post(String url, Map<String, Object> params) {
    return post(url, params, null);
  }

  public static String post(String url, Map<String, Object> params, Map<String, String> headers) {
    UrlEncodedFormEntity entity = null;
    if (params != null && params.size() > 0) {
      List<NameValuePair> nvps = new ArrayList<>(params.size());
      for (Map.Entry<String, Object> param : params.entrySet()) {
        nvps.add(new BasicNameValuePair(param.getKey(), param.getValue().toString()));
      }
      entity = new UrlEncodedFormEntity(nvps, Charset.forName(DEFAULT_CHARSET));
    }
    byte[] respBytes = post(url, entity, headers);
    try {
      return new String(respBytes, DEFAULT_CHARSET);
    } catch (UnsupportedEncodingException ignore) {
      //永远不可能抛出该异常
      throw new RuntimeException(ignore);
    }
  }

  public static String postJson(String url, String body) {
    return postJson(url, body, null);
  }

  public static String postJson(String url, String body, Map<String, String> headers) {
    StringEntity entity = new StringEntity(body, DEFAULT_CHARSET);
    entity.setContentType("application/json");
    byte[] respBytes = post(url, entity, headers);
    try {
      return new String(respBytes, DEFAULT_CHARSET);
    } catch (UnsupportedEncodingException ignore) {
      //永远不可能抛出该异常
      throw new RuntimeException(ignore);
    }
  }

  private static byte[] post(String url, HttpEntity entity, Map<String, String> headers) {
    HttpPost post = new HttpPost(url);
    if (entity != null) {
      post.setEntity(entity);
    }
    return execute(post, headers);
  }

  private static byte[] execute(HttpUriRequest req, Map<String, String> headers) {
    //===请求header
    if (headers != null && headers.size() > 0) {
      for (Map.Entry<String, String> entry : headers.entrySet()) {
        req.setHeader(entry.getKey(), entry.getValue());
      }
    }
    try {
      return httpClient.execute(req, responseHandler);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public static void main(String[] args) {

    //===1.get请求
    String get = Http.get("https://www.baidu.com/");
    System.out.println("get = " + get);


       /* //===2.post for json
        Map<String, Object> param = new HashMap<>();
        param.put("name", "google");
        String json = JSONObject.toJSONString(param);
        System.out.println("json = " + json);
        String post = Http.postJson("http://localhost:9095/test/add", json);
        System.out.println("post = " + post);

        //===3.post common
        String body = Http.post("http://localhost:9095/test/add", param);
        System.out.println("body = " + body);*/
  }
}
